import React, { Component } from 'react';
import { StyleSheet, Text, View, Image, ScrollView, TextInput, TouchableOpacity } from "react-native";
import { NavigationEvents } from 'react-navigation';
import navigationSeevice from '../../../../../components/navigation/navigationSeevice';
import { style } from '../../../../../theme/style';
import { GLOBAL } from '../../../../../config/global';
import HTTP from '../../../../../utils/http';
import { API, API_GENERATE } from '../../../../../config/api';
import Dictionary from '../../../../../utils/dictionary';
import { CURRENCY } from '../../../../../utils/helper';
import { BockCpt } from './_components/BockCpt';
import { BaseInfoCpt } from './_components/BaseInfoCpt';
import { ContractCpt } from './_components/ContractCpt';
import { AddressBockCpt } from './_components/AddressBockCpt';
import { CreditCpt } from './_components/CreditCpt';
import { GoodsBockCpt } from './_components/GoodsBockCpt';
import { GoodsCpt } from './_components/GoodsCpt';
import { CommonDialog } from '../../../../../components/common/Dialog';


const locked = require('../../../../../imgs/customer/suoding.png');
const unLock = require('../../../../../imgs/customer/zhengchang.png');
const expired = require('../../../../../imgs/customer/expired.png');
const query = require('../../../../../imgs/global/query.png');
let qualificationTypeObj = {};
let companyPropObj = {};
let corpObj = {}
const scale = GLOBAL.SCALE;

export class EnBaseInfoComponent extends Component {
	static navigationOptions = {
		header: null
	}

	constructor(props) {
		super(props);
		const { data } = props;
		this.state = {
			detail: data || {},
			enableScrollViewScroll: true,
			modalVisible: false,
			upgradeModalVisible: false
		}

	}

	async	componentWillMount () {
		this._init();
	}

	// componentWillReceiveProps (props) {
	// 	const { data } = props;
	// 	this.setState({
	// 		detail:data||{}
	// 	},()=>{
	// 		this._init()
	// 	})
	// }

	//初始数据处理
	_init = () => {
		this.getStorageDate();
		this.getCompanyGoods();
	}

	//企业经营品类
	async	getCompanyGoods () {
		const { detail } = this.state;
		const { companyInfoVO } = detail || {};
		const { choice } = this.props || {};
		const reponse = await HTTP.POST(API_GENERATE(API.CUSTOMER_DETAIL), { companyId: companyInfoVO.companyId, sourceFlag: 1, corpId: choice.corpId });
		this.setState({ companyGoodsTreeList: reponse });
	}

	async getStorageDate () {
		const { detail } = this.state;
		const { companyInfoVO, corpTypeList, qualificationListPage } = detail || {};
		//企业类型/合作关系/资质类型
		let companyPropList = await Dictionary.get("COMPANY_PROP");
		let corpResult = await Dictionary.get("EC_CORP_TYPE");
		let qualificationTypeList = await Dictionary.get("EC_QUALIFICATION_TYPE");
		
		qualificationTypeList.forEach(item => {
			const { dictKey, dictName } = item;
			qualificationTypeObj[dictKey] = dictName;
		});

		qualificationListPage && qualificationListPage.rows && qualificationListPage.rows.map((item, index) => {
			item.qualificationTypeText = qualificationTypeObj[item.qualificationType];
		})

		companyPropList.forEach(item => {
			const { dictKey, dictName } = item;
			companyPropObj[dictKey] = dictName;
		});

		corpResult.forEach(item => {
			const { dictKey, dictName } = item;
			corpObj[dictKey] = dictName;
		});

		let companyPropStr = companyInfoVO.companyType && companyPropObj[companyInfoVO.companyType];
		const companyCorpStr = corpTypeList && corpTypeList.map(item => {
			return corpObj[item.corpType];
		}).join('/');

		this.setState({
			companyPropStr,
			companyCorpStr,
			detail,
			qualificationTypeObj
		})
	}

	//获取基本信息
	_getInfoBase = (sendDate) => {
		let { ifEdit } = this.props;
		let { companyPropStr, companyCorpStr } = this.state;
		let { companyInfoVO, acctList } = sendDate || {};
		let { creditLevel, companyName, companyNatureName, registerFund, linkPhone, registAddress, creditCode, creditFile, taxCode, openBankName,
			openAcctNo, invoicePhoneNo, invoiceFileId, invoiceAddress, expireDate, isLock, countryName, provinceName, registerFundCurrency,
			cityName, legalName, registerDate, mdmCode } = companyInfoVO || {};
		let infoBase = [{ lable: '企业名称', value: [companyName || '--'], icon: isLock ? locked : unLock, isMdmCode: mdmCode ? false : true }];
		infoBase.push({
			lable: '企业评级', value: [creditLevel || '1级'], icon: query,
			iconStyle: { width: 10 * scale, height: 10 * scale },
			iconPress: () => { this.setState({ modalVisible: true }) },
			// rightButtonText: creditLevel == '1' && ifEdit ? '评级升级' : '',
			// rightButtonPress: () => { this.setState({ upgradeModalVisible: true }) }
		});
		infoBase.push({ lable: '国家及地区', value: [`${countryName || ''}${provinceName || ''}${cityName || ''}`] });
		infoBase.push({ lable: '企业属性', value: [companyPropStr || '--'] });
		infoBase.push({ lable: '资本性质', value: [companyNatureName || '--'] });
		infoBase.push({ lable: '合作关系', value: [companyCorpStr || '--'] });
		infoBase.push({ lable: '注册资本', value: [(registerFund || '--') + `万${CURRENCY.getUnit(registerFundCurrency).text}`] });
		infoBase.push({ lable: '注册日期', value: [registerDate && registerDate.substring(0, 10) || '--'] });
		infoBase.push({ lable: '法人代表', value: [legalName || '--'] });
		infoBase.push({ lable: '企业联系电话', value: [linkPhone || '--'] });
		infoBase.push({ lable: '企业地址', value: [registAddress || '--'] });
		infoBase.push({ lable: '统一信用代码', value: [creditCode || '--'] });
		infoBase.push({ lable: '开票信息', value: [], type: 'T' }); //这个数据结构只针对企业基本信息模块-->不传value则默认为副标题
		infoBase.push({ lable: '纳税人识别号', value: [taxCode || '--'] });
		infoBase.push({ lable: '开户行', value: [openBankName || '--'] });
		infoBase.push({ lable: '开户行帐号', value: [openAcctNo || '--'] });
		infoBase.push({ lable: '开票电话', value: [invoicePhoneNo || '--'] });
		infoBase.push({ lable: '开票地址', value: [invoiceAddress || '--'] });
		infoBase.push({ lable: '银行信息', value: [], type: 'T' });//这个数据结构只针对企业基本信息模块-->不传value则默认为副标题
		acctList && acctList.length && acctList.map((item, index) => {
			infoBase.push({ lable: '开户行', value: [item.openBankName || '--'] })
			infoBase.push({ lable: '开户行帐号', value: [item.openAcctNo || '--'] })
		})
		infoBase.push({ lable: '附件信息', value: [], type: 'T' })
		infoBase.push({ lable: '营业执照', value: [`有效期至${expireDate && expireDate.substring(0, 10) || '--'}`], fileId: creditFile, type: 'C' })
		infoBase.push({ lable: '开票附件', value: ['invoice'], fileId: invoiceFileId, type: 'I' })

		return infoBase;
	}

	//检查资质是否有过期
	_getQualificationInfo (data) {
		const { rows } = data || {};
		const { qualificationTypeObj } = this.state;
		let isExpired;

		if (rows && rows.length) {
			for (let i = 0; i < rows.length; i++) {
				if (rows[i].isExpired == '-1') {
					isExpired = true;
					break;
				}
			}
		}
		return { isExpired, qualificationTypeObj };
	}

	//点击企业信息标题查看操作日志
	_onBaseInfoTitlePress (companyId) {
		navigationSeevice.navigate('LogListPage', { companyId })
	}

	//查看资质详情or新增
	_onCreditPress (data, type) {
		const { ifEdit } = this.props;
		const { detail } = this.state;
		const { companyInfoVO } = detail || {};
		//跳转传参传的太乱，后期改版新增资质时再调整
		navigationSeevice.navigate('EnterpriseEditQualificationPage', {
			qualificationVO: { companyId: companyInfoVO.companyId, },
			qualificationType: {
				dictKey: data.qualificationType,
				dictName: data.qualificationTypeText
			},
			companyName: companyInfoVO.companyName,
			ifEdit: ifEdit || type == 'add' ? true : false, //详情页是否可操作
			qualificationInfo: data
		})
	}

	async refreshData () {
		const { detail } = this.state;
		const { companyInfoVO } = detail || {};
		const { choice } = this.props || {};
		const responseData = await HTTP.POST(API_GENERATE(API.GET_CUSTOMER_DETAIL), {
			companyId: companyInfoVO.companyId,
			corpId: choice.corpId
		});
		this.setState({
			detail: responseData
		}, () => {
			this._init()
			this.props.review(responseData)
		})
		console.log(responseData)
	}

	_uploadPress () {
		const { detail } = this.state;
		const { qualificationListPage, companyInfoVO } = detail || {};
		const { choice } = this.props || {};
		navigationSeevice.navigate('EnterpriseUploadPage',
			{
				companyId: companyInfoVO.companyId,
				corpId: choice.corpId,
				type: 'upload',
				refresh: () => {
					this.refreshData()
				},
			}
		)
	}

	// 基本信息模版
	_viewBase = (sendData, index, length) => {
		return (
			<BaseInfoCpt data={sendData} key={index} />
		)
	}

	// 企业成员
	_viewContract = (sendData, index, length) => {
		const { ifEdit, data, choice } = this.props;
		return (
			<ContractCpt choice={choice} data={sendData} baseData={data.companyInfoVO} key={index} index={index} length={length} ifEdit={ifEdit} init={() => this.refreshData()} />
		)
	}

	// 企业资质
	_viewCredit = (sendData, index, length, refresh) => {
		const { ifEdit } = this.props;
		const { qualificationAddress } = sendData;
		return (
			<CreditCpt data={sendData} key={index} index={index} length={length} ifEdit={ifEdit}
				onPress={() => this._onCreditPress(sendData, 'add')}
				checkQualificationImage={() => { qualificationAddress && this._onCreditPress(sendData) }} />
		)
	}

	// 企业
	_viewGoods = (sendData, index, length) => {
		const { ifEdit, data, choice } = this.props;
		return (
			<GoodsCpt choice={choice} data={sendData} baseData={data.companyInfoVO} key={index} index={index} length={length} ifEdit={ifEdit} />
		)
	}

	_closeFlatListFn = () => {
		this.setState({ enableScrollViewScroll: false });
		if (this._myScroll && this._myScroll.contentOffset === 0
			&& this.state.enableScrollViewScroll === false) {
			this.setState({ enableScrollViewScroll: true });
		}
	}

	_renderToastWrap = () => {
		return (
			<View>
				<Text style={styles.toastText}>1.资信评级1级不支持授信订单、保证金业务、暂定价商品</Text>
				<Text style={styles.toastText}>2.资信评级2级支持做授信订单、保证金业务、暂定价商品</Text>
			</View>
		)
	}

	_renderAssignToastWrap = () => {
		return (
			<View>
				<View style={[styles.row, { marginBottom: 12 * scale }]}>
					<Text style={{ fontSize: 12 * scale, marginRight: 3 * scale }}>企业升级：</Text>
					<View style={styles.circle}>
						<View style={styles.selectedCircle}></View>
					</View>
					<Text style={{ fontSize: 12 * scale }}>2级</Text>
				</View>
				<View style={[styles.row, { marginBottom: 5 * scale }]}>
					<Text style={{ color: 'red', marginRight: 3 * scale }}>*</Text><Text style={{ fontSize: 12 * scale }}>备注：</Text>
				</View>
				<TextInput
					style={styles.textInput}
					placeholder={"请输入备注，限定1000字。"}
					placeholderTextColor={"#B4B8C0"}
					value={this.state.comments}
					maxLength={1000}
					multiline={true}
					onChangeText={(comments) => this.setState({ comments })}
				/>
				<TouchableOpacity style={styles.btn} onPress={() => { this._submit() }}>
					<Text style={styles.btnText}>升级</Text>
				</TouchableOpacity>
			</View>
		)
	}

	render () {
		const { ifEdit, id, status, choice } = this.props;
		const { detail, companyGoodsTreeList, modalVisible, upgradeModalVisible } = this.state;
		const { companyInfoVO, contactorList, addressListPage, qualificationListPage, bizCompanyGoodsList, goodsTreeList } = detail || {};
		const { rows } = qualificationListPage || {};
		let infoBase = detail && this._getInfoBase(detail);
		let qfcInfo = qualificationListPage && this._getQualificationInfo(qualificationListPage);
		return (
			<View onStartShouldSetResponderCapture={() => {
				this.setState({ enableScrollViewScroll: true });
			}}>
				<ScrollView ref={myScroll => (this._myScroll = myScroll)} scrollEnabled={this.state.enableScrollViewScroll} showsVerticalScrollIndicator={false}>
					<NavigationEvents
						onWillFocus={({ action }) => {
							this._init();
						}}
					/>
					{
						detail ?
							<View style={styles.baseInfoContainer}>
								<BockCpt titleStyle={styles.basoInfoTitleStyle}
									onTitlePress={() => { this._onBaseInfoTitlePress(companyInfoVO.companyId) }}
									renderView={this._viewBase}
									data={{ title: '企业信息', listData: infoBase, visible: true }} />
								<BockCpt
									renderView={this._viewContract}
									data={{ title: '企业成员', listData: contactorList, member: true, ifEdit }}
									navigateTo={() => {
										navigationSeevice.navigate('EnterpriseEditContactPage', {
											companyName: companyInfoVO.companyName,
											countryCode: companyInfoVO.countryCode,
											companyId: companyInfoVO.companyId,
											choice: choice,
											init: () => this.refreshData()
										})
									}}
									refresh={() => this._init()}
									type={'qycy'}
								/>
								<BockCpt
									titleIcon={qfcInfo && qfcInfo.isExpired ? expired : null}
									renderView={this._viewCredit}
									data={{ title: '企业资质', listData: rows, upload: true }}
									checkQualificationImage={() => { this._uploadPress() }}
									refresh={() => this._init()} />
								<AddressBockCpt
									oncloseFlatListFn={this._closeFlatListFn}
									data={{ title: '出入库地址', listData: addressListPage, }}
									baseData={{ ifEdit, status, id, choice, companyId: companyInfoVO.companyId, companyName: companyInfoVO.companyName }}
								/>
								{/**审批中取详情的goodsTreeList */}
								<GoodsBockCpt
									renderView={this._viewGoods}
									data={{ title: '经营品类', listData: bizCompanyGoodsList }}
									baseData={{ ifEdit, status, id, choice, companyInfoVO, companyGoodsTreeList: status ? companyGoodsTreeList : goodsTreeList }} />
							</View>
							: null
					}

					<CommonDialog modalVisible={modalVisible} title={'提示'} renderCustom={this._renderToastWrap} onClosePress={() => { this.setState({ modalVisible: false }) }} />
					<CommonDialog modalVisible={upgradeModalVisible} title={'提示'} onClosePress={() => { this.setState({ upgradeModalVisible: false }) }} renderCustom={this._renderAssignToastWrap} />
				</ScrollView>
			</View>

		)
	}
}


const styles = StyleSheet.create({
	baseInfoContainer: {
		flex: 1,
		flexDirection: 'column',
		alignItems: 'center',
		paddingLeft: 14 * scale,
		paddingRight: 14 * scale,
	},
	basoInfoTitleStyle: {
		borderWidth: 1 * scale,
		borderColor: style.color.themeColor,
		color: style.color.themeColor,
		borderRadius: 8 * scale,
		padding: 5 * scale
	},
	toastText: {
		fontSize: 12 * scale,
		marginBottom: 8 * scale
	},
	circle: {
		width: 14 * scale,
		height: 14 * scale,
		borderStyle: 'solid',
		borderColor: style.color.themeColor,
		borderWidth: 1 * scale,
		borderRadius: 7 * scale,
		alignItems: 'center',
		justifyContent: 'center',
		marginRight: 6 * scale,
	},
	selectedCircle: {
		width: 6 * scale,
		height: 6 * scale,
		borderStyle: 'solid',
		borderColor: style.color.themeColor,
		borderWidth: 1 * scale,
		borderRadius: 3 * scale,
		backgroundColor: style.color.themeColor,
	},
	btn: {
		backgroundColor: style.color.themeColor,
		borderRadius: 14 * scale,
		marginLeft: '32%',
		marginRight: '32%',
		marginTop: 10 * scale,
		paddingTop: 10 * scale,
		paddingBottom: 10 * scale,
	},
	btnText: {
		color: '#fff',
		textAlign: 'center',
		fontSize: 14 * scale,
		fontWeight: 'bold'
	},
	row: {
		flexDirection: 'row',
		alignItems: 'center',
	},
	textInput: {
		borderWidth: 1 * scale,
		borderColor: '#000',
		borderRadius: 4 * scale,
		padding: 10 * scale,
		height: 122 * scale,
		fontSize: 12 * scale,
	},
})